package com.wuye.web.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.wuye.utils.RedisConstant;
import com.wuye.utils.Result;
import com.wuye.web.system.entity.LiveUser;
import com.wuye.web.system.entity.LoginParam;
import com.wuye.web.system.entity.SysUser;
import com.wuye.web.system.service.LoginService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/")
public class LoginController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private LoginService loginService;

    @PostMapping("/captcha")
    @ApiOperation("获取验证码")
    public Result captcha(){
        //获取验证码对象
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200,40,4,11);
        //获取验证码内容
        String captchaCode = lineCaptcha.getCode();
        //获取验证码图片内容
        String imageBase64 = lineCaptcha.getImageBase64();
        //随机验证码id，用于存入redis中的key
        String captchaId = UUID.randomUUID().toString();
        //将验证码存入redis

        redisTemplate.opsForValue().set(RedisConstant.CAPTCHA_PRE+captchaId,captchaCode,RedisConstant.CAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS);
        Map<String,String> map = new HashMap<>();
        map.put("captchaId",captchaId);
        map.put("imageBase64",imageBase64);
        return Result.success(map);
    }

    @PostMapping("/login")
    @ApiOperation("登录处理")
    public Result login(
            @RequestBody
            @Valid
            @ApiParam(value = "登录需要参数",required = true)
            LoginParam loginParam){
        return loginService.login(loginParam);
    }
    @PostMapping("/logout")
    @ApiOperation("安全退出")
    public Result logout(){
        return loginService.logout();
    }

    /*@GetMapping("/hello")
    public Result hello(){
        return Result.success("hello");
    }*/

    @GetMapping("/getInfo")
    @ApiOperation("查看个人信息")
    public Result getInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof SysUser){
            SysUser sysUser = (SysUser) principal;
            return Result.success(sysUser);
        }else {
            LiveUser liveUser = (LiveUser) principal;
            return Result.success(liveUser);
        }
    }
}
